/**
 * Created by litao on 2017/3/6.
 */

//查询地图及底图定义
var mapObject = (function () {
    var instantiated;
    var map = null;

    function init() {
        return {
            initMap: function (args) {
                var tdt = layerUtil.getTdt(false);
                map = new OpenLayers.Map({
                    div: args,
                    allOverlays: true,
                    layers: tdt,
                    projection: "EPSG:4326",
                    displayProjection: new OpenLayers.Projection("EPSG:4326"),
                    numZoomLevels: 18,
                    center: [111.203, 29.456],
                    zoom: 7
                });
                map.addControl(new OpenLayers.Control.MousePosition());
            },
            getMap: function () {
                return map;
            }
        }
    };
    return {
        getInstance: function (args) {
            if (!instantiated) {
                instantiated = init(args);
            }
            return instantiated;
        }
    }
})();
//图层定义
var layerUtil = (function () {
    var l1 = new OpenLayers.Layer.WMTS({
        name: "tdt_ditu",
        url: "http://t0.tianditu.com/vec_c/wmts",
        layer: "vec",
        style: "default",
        matrixSet: "c",
        format: "tiles",
        isBaseLayer: true
    })
    var l2 = new OpenLayers.Layer.WMTS({
        name: "tdt_ditubz",
        url: "http://t0.tianditu.com/cva_c/wmts",
        layer: "cva",
        style: "default",
        matrixSet: "c",
        format: "tiles",
        isBaseLayer: false
    });

    //绘制矢量查询框
    var drawLayer = new OpenLayers.Layer.Vector("drawExtent", {
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
                strokeColor: "blue",
                strokeOpacity: 0.4,
                fillColor: "#993300",
                fillOpacity: 0
            })
        })
    });
    var OutlineListeners = {
        featureclick: function (e) {
            if (!e.feature.id) return;
            layerUtil.selectFeature(e.feature);
            var rows = $('#pierTable')[0].rows;
            for (var i = 0; i < rows.length; i++) {
                $(rows[i]).removeClass('active');
                if (parseInt(rows[i].firstChild.innerHTML) == (e.feature.attributes['id'])) {
                    $(rows[i]).addClass('active');
                    $('.dataTables_scrollBody').scrollTop(rows[i].offsetTop);
                }
            }
            return false;
        },
    };
    var compareArray = ["OneMap","OneMap15","NavigationMap"];
    var wmsLayer = new OpenLayers.Layer.WMS("WMS",
        "http://60.194.14.226:7090/onemap/rest/wms",
        {layers: 'WGS84'});

    var titleresolutions_z = new Array(20);
    var levelzero = 0.703125;
    for (var z = 0; z < 16; ++z) {
        titleresolutions_z[z] = levelzero / Math.pow(2, z);
    }
    // titleresolutions_z[0] = 0.703125;
    // titleresolutions_z[1] = 0.3515625;
    // titleresolutions_z[2] = 0.17578125;
    // titleresolutions_z[3] = 0.087890625;
    // titleresolutions_z[4] = 0.0439453125;
    // titleresolutions_z[5] = 0.02197265625;
    // titleresolutions_z[6] = 0.010986328125;
    // titleresolutions_z[7] = 0.0054931640625;
    // titleresolutions_z[8] = 0.00274658203125;
    // titleresolutions_z[9] = 0.001373291015625;
    // titleresolutions_z[10] = 0.0006866455078125;
    // titleresolutions_z[11] = 0.00034332275390625;
    // titleresolutions_z[12] = 0.000171661376953125;
    // titleresolutions_z[13] = 0.0000858306884765625;
    // titleresolutions_z[14] = 0.00004291534423828125;
    // titleresolutions_z[15] = 0.000021457672119140625;

    var wmtsLayer = new OpenLayers.Layer.WMTS({
            name: "WMTS",
            url: "http://60.194.14.226:7090/onemap/rest/wmts",
            requestEncoding: 'KVP',
            layer: "satImage",
            matrixSet: "satImage",
            style: "default",
            tileOrigin: new OpenLayers.LonLat(-180, 90),
            serverResolutions: titleresolutions_z,
            isBaseLayer: true,
            params:{"account":"admin","passwd":"admin123"}

        }
    );
    var oneMapLayer = new OpenLayers.Layer.WMTS({
            name: "OneMap",
            url: "http://123.56.192.226:7090/stbserver/rest/wmts",
            requestEncoding: 'KVP',
            layer: "satImage",
            //原点
            tileOrigin:new OpenLayers.LonLat(-180,90),
            style: "default",
            //format:"image/png",
            matrixSet: "satImage",
            serverResolutions: titleresolutions_z,
            isBaseLayer: false,
            visibility:false
        }
    );
    var oneMap15Layer = new OpenLayers.Layer.WMTS({
            name: "OneMap15",
            url: "http://60.194.14.226:7090/onemap/rest/wmts",
            requestEncoding: 'KVP',
            layer: "satImage",
            matrixSet: "satImage",
            style: "default",
            tileOrigin: new OpenLayers.LonLat(-180, 90),
            serverResolutions: titleresolutions_z,
            isBaseLayer: false,
            params:{"account":"admin","passwd":"admin123"},
            visibility:false
        }
    );
    var naviLayer = new OpenLayers.Layer.WMTS({
            name: "NavigationMap",
            url: "http://60.194.14.226:7090/rest/wmts",
            requestEncoding: 'KVP',
            layer: "satImage",
            matrixSet: "satImage",
            style: "default",
            tileOrigin: new OpenLayers.LonLat(-180, 90),
            serverResolutions: titleresolutions_z,
            isBaseLayer: false,
            params:{"account":"admin","passwd":"admin123"}
        }
    );
    //查询到的矢量图层定义
    var resultLayer = new OpenLayers.Layer.Vector("company", {
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
                strokeColor: "red",
                strokeWidth: 1,
                strokeOpacity: 1,
                fillColor: "yellow",
                fillOpacity: 0
            })
        }),
        eventListeners: OutlineListeners
    });

    var coverLayer = new OpenLayers.Layer.Vector("cover", {
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
                strokeColor: "#00FFFF",
                strokeWidth: 1.5,
                strokeOpacity: 1,
                fillColor: "yellow",
                fillOpacity: 0.2
            })
        }),
        eventListeners: OutlineListeners
    });

    //临时高亮矢量图层
    var HighLightLayer = new OpenLayers.Layer.Vector("highlight", {
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
                strokeColor: "#00FFFF",
                strokeWidth: 1.8,
                strokeOpacity: 1,
                fillColor: "blue",
                fillOpacity: 0.2
            })
        })
    });
    var lastFeature;

    //省份图层
    var provinceLayer = new OpenLayers.Layer.Vector("province", {
        styleMap: new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
                strokeColor: "red",
                strokeWidth: 0.8,
                strokeOpacity: 1,
                fillColor: "blue",
                fillOpacity: 0
            })
        })
    });
    //工厂图层
    var companyLayer = new OpenLayers.Layer.Vector("company", {
        styleMap: new OpenLayers.Style({
            strokeColor: "${COLOR}",
            strokeOpacity: 1,
            strokeWidth: 0.6,
            fillColor: "${COLOR}",
            fillOpacity: "${FILL}"
        }),
        eventListeners: OutlineListeners
    });
    //单个工厂范围图层
    var single_comLayer = new OpenLayers.Layer.Vector("single_com", {
        styleMap: new OpenLayers.Style({
            strokeColor: "red",
            strokeOpacity: 1,
            strokeWidth: 1,
            fillColor: "red",
            fillOpacity: 0
        })
    });

    //标注图层
    var markersLayer = new OpenLayers.Layer.Markers("Markers");
    return {
        resultLy: resultLayer,
        drawLayer: drawLayer,
        wmsLayer: wmsLayer,
        wmtsLayer: wmtsLayer,
        hightlayer: HighLightLayer,
        coverLayer: coverLayer,
        provinceLayer: provinceLayer,
        companyLayer: companyLayer,
        single_comLayer: single_comLayer,
        markersLayer: markersLayer,
        compareArray:compareArray,
        bzLayer: l2,
        dtLayer: l1,
        oneMapLayer:oneMapLayer,
        oneMap15Layer:oneMap15Layer,
        naviLayer:naviLayer,
        getTdt: function (bool) {
            if (bool) {
                return [l1, l2];
            } else {
                return [oneMapLayer,oneMap15Layer,naviLayer];//[l1,oneMapLayer,oneMap15Layer,naviLayer];
            }

        },
        clearDrawLy: function () {
            if (drawLayer.features.length > 0) {
                drawLayer.removeAllFeatures();
            }
        },
        clearResultLy: function () {
            if (resultLayer.features.length > 0) {
                resultLayer.removeAllFeatures();
            }
        },
        clearMapView: function () {
            var _map = mapObject.getInstance().getMap();
            if (resultLayer.features.length > 0) {
                resultLayer.removeAllFeatures();
            }
            ;
            if (_map.getLayersByName('WMS')[0]) {
                _map.removeLayer(_map.getLayersByName('WMS')[0]);
            }
            var pop_len = _map.popups.length;
            if (pop_len > 0) {
                for (var i = 0; i < pop_len; i++) {
                    _map.removePopup(_map.popups[i]);
                }
            }
        },
        selectFeature: function (feature) {
            var map = mapObject.getInstance().getMap();
            //模拟点击
            var pop_len = map.popups.length;
            if (pop_len > 0) {
                for (var i = 0; i < pop_len; i++) {
                    map.removePopup(map.popups[i]);
                }
            }
            if (!lastFeature) {
                lastFeature = feature;
                lastFeature.renderIntent = "default";
                if (lastFeature.layer) {
                    lastFeature.layer.drawFeature(lastFeature);
                }

            }
            lastFeature = feature;
            feature.renderIntent = "select";
            feature.layer.drawFeature(feature);

            var lon = feature.geometry.getBounds().getCenterLonLat();
            var popup = new OpenLayers.Popup.FramedCloud(feature.id,
                feature.geometry.getBounds().getCenterLonLat(), null,
                "<div style='font-size:.8em;width:200px;'>" + "<br>名称：" + feature.attributes['name'] + "<br>省份：" + feature.attributes['province'] + "<br>业主：" + feature.attributes['owner']+"<br>具体位置：" + feature.attributes['location']
                + "</div>", null, true,
                function () {
                    map.removePopup(feature.popup);
                    if (feature.popup) {
                        map.removePopup(feature.popup);
                        feature.popup.destroy();
                        feature.popup = null;
                    }
                });
            feature.popup = popup;
            map.addPopup(popup);
        }
    }
})();
//地图操作工具
var mapTools = (function () {
    var draw_control = new OpenLayers.Control.Pan();
    var _mapType = null;
    return {
        toolsActive: function (mapType) {
            draw_control.deactivate();
            _mapType = mapType;
            switch (mapType) {
                case 'selRect':
                    layerUtil.clearDrawLy();
                    drawUtil.addInteraction("Box");
                    break;
                case 'selPol':
                    layerUtil.clearDrawLy();
                    drawUtil.addInteraction("Polygon");
                    break;
                case 'fullMap':
                    var map = mapObject.getInstance().getMap();
                    map.setCenter(new OpenLayers.LonLat(107.07, 38.02), 4);
                    var pop_len = map.popups.length;
                    if (pop_len > 0) {
                        for (var i = 0; i < pop_len; i++) {
                            map.removePopup(map.popups[i]);
                        }
                    }
                    break;
                case 'clear':
                    layerUtil.clearMapView();
                    break;
            }
        },
        drawToggle: function () {
            draw_control.trigger();
        },
        getMapType: function () {
            return _mapType;
        }
    }
})();

